package com.xianrenit.xianrenpuzi.manager.controller;

import com.xianrenit.xianrenpuzi.manager.service.CodeImgService;
import com.xianrenit.xianrenpuzi.manager.service.SysUserService;
import com.xianrenit.xianrenpuzi.model.dto.sys.LoginDto;
import com.xianrenit.xianrenpuzi.model.entity.sys.SysUser;
import com.xianrenit.xianrenpuzi.model.result.Result;
import com.xianrenit.xianrenpuzi.model.vo.sys.LoginVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
//因为前端携带cookie跨域访问，所以需要配置允许跨域访问
// originPatterns:配置允许跨域访问的服务器
// allowCredentials: 允许携带cookie跨域访问
// allowedHeaders: 允许携带请求头跨域访问
//@CrossOrigin(originPatterns = "*", allowCredentials = "true", allowedHeaders = "*")
@RequestMapping("/admin/system/index")
@Tag(name = "Index模块")
public class IndexController {
    @Resource
    SysUserService sysUserService;
    @Resource
    CodeImgService codeImgService;
    //以后后端的大部分接口 都需要登录之后才能执行
    //需要验证登录状态： 请求头是否携带token、token在redis中是否有对应的缓存
    //注销接口
    @Operation(summary = "注销方法")
    @DeleteMapping("logout")
    public Result logout(@Parameter(name="token" , description = "登录令牌",in = ParameterIn.HEADER)
                             @RequestHeader("token")String token){
        //删除redis中的登录状态
        sysUserService.logout(token);
        return Result.ok();
    }

    //获取用户信息接口
    @Operation(summary = "获取用户信息")
    @GetMapping("/userinfo")
    public Result getUserInfo(){
        SysUser sysUser = sysUserService.getUserInfo();
        return Result.ok(sysUser);
    }
    @Operation(summary = "获取验证码")
    @GetMapping("codeImg")
    public Result generateCodeImg(){
        //开发中少用map
        Map<String,String> map = codeImgService.generateCodeImg();
        return Result.ok(map);
    }
    @Operation(summary = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto) {
//        try {
        LoginVo loginVo = sysUserService.login(loginDto);
        // 200 +  Result(code=200)
        return Result.ok(loginVo);
//        } catch (Exception e) {
//            // 200 +  Result(code=-1)
//            return Result.fail().message(e.getMessage());
//        }
    }
}
